<?php
namespace Middleware;

class CSRFTOKEN
{
    //csrf中间件
    private $salt = 'aabbcc';
    //如果有post过来的表单 认证
    function request($request){
        $post = $request['post'];
        if($post == [])
            return $request;
        if(!array_key_exists('csrftoken',$request['post']) || !array_key_exists('csrftoken',$request['cookie'])) {
            echo 'csrftoken not found';
            return false;
        }
        $sign = $request['post']['csrftoken'];
        $token = $request['cookie']['csrftoken'];
        //校验token
        if(! ($this->encrypt($token) == $sign)) {
            echo 'token error';
            return false;
        }
        return $request;
    }
    //在表单中生成csrftoken
    function response($html){
        $token = uniqid();
        $sign = $this->encrypt($token);
        setcookie('csrftoken',$token);
        $html = preg_replace("/%csrftoken%/",$sign,$html);
        return $html;
    }

    function encrypt($token){
        return md5($token.$this->salt);
    }
}